import React, { useEffect, useState, useCallback } from 'react';
import MethodFilterBar from './MethodFilterBar';
import MethodTable from './MethodTable';
import ApiAnalysisTab from './ApiAnalysisTab';
import ChangeAnalysisTab from './ChangeAnalysisTab';
import DubboAnalysisTab from './DubboAnalysisTab';
import DatabaseAnalysisTab from './DatabaseAnalysisTab';
import DependencyAnalysis from './DependencyAnalysisTab';
import ConfigManagement from './ConfigManagementTab';
import ScanRecords from './ScanRecords';
import BasicInfo from './BasicInfoTab';
import CodeScaleAnalysis from './CodeScaleAnalysisTab';
import { UnitInfoStatusBadges, CodeDuplicationTable, ExportProgressModal } from './components';
import { manualTriggerScan, manualTriggerScanByType, getUnit, getTopComplexityMethods, fetchUnitList } from '../../services/unit';
import { fetchMethodPageQuery, exportMethods, getExportStatus, downloadExportFile } from '../../services/method';
import { Spin, Button, Alert, Card, Row, Col, Empty, Table, message, Dropdown, Tooltip, Input, Select, Collapse, Tag, Radio, Pagination, Modal } from 'antd';
import { useNavigate } from 'react-router-dom';
import {
    InfoCircleOutlined,
    FunctionOutlined,
    DatabaseOutlined,
    FileTextOutlined,
    BarChartOutlined,
    ApiOutlined,
    SettingOutlined,
    BugOutlined,
    SyncOutlined,
    CodeOutlined,
    EditOutlined,
    ArrowLeftOutlined,
    PlayCircleOutlined,
    CaretDownOutlined,
    ThunderboltOutlined,
    LineChartOutlined,
    ShareAltOutlined,
    CustomerServiceOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import CallGraphTab from './CallGraphTab';
import AssistantTab from './AssistantTab';
import type { TablePaginationConfig } from 'antd/es/table';
import { buildFileLink, formatRelativePath as formatRelativePathUtil, convertSshToHttp } from '../../utils/gitUrlUtils';
import { convertDaysToDateQuery, formatQueryCondition } from './utils';

interface UnitDetailPageProps {
    unitId: string;
}

// UnitInfoStatusBadges 组件已移至 ./components/UnitInfoStatusBadges.tsx

// BasicInfo 组件已移至 ./BasicInfoTab/index.tsx

// 方法分析组件（原来的方法表格）
const MethodAnalysis: React.FC<{
    data: any[];
    pagination: any;
    loading: boolean;
    queryInfo: string;
    unitInfo: any;
    onSearch: (values: any, pager?: any) => void;
    onTableChange: (pager: any, filters: any, sorter: any) => void;
    onClearQuery: () => void;
    onExport: (filterValues: any) => void;
    exportLoading: boolean;
}> = ({ data, pagination, loading, queryInfo, unitInfo, onSearch, onTableChange, onClearQuery, onExport, exportLoading }) => {
    return (
        <div>
            {/* 查询条件说明 */}
            {queryInfo && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                    <Alert
                        message={queryInfo}
                        type="info"
                        showIcon
                        style={{
                            flex: 1,
                            backgroundColor: '#e6f7ff',
                            border: '1px solid #91d5ff',
                            margin: 0
                        }}
                        closable
                    />
                    <Button
                        type="link"
                        size="small"
                        onClick={onClearQuery}
                        style={{ color: '#1890ff' }}
                    >
                        清除条件
                    </Button>
                </div>
            )}

            <MethodFilterBar
                onSearch={onSearch}
                onExport={onExport}
                exportLoading={exportLoading}
            />

            <Spin spinning={loading}>
                <MethodTable
                    data={data}
                    pagination={pagination}
                    loading={loading}
                    onChange={onTableChange}
                    unitInfo={unitInfo}
                />
            </Spin>
        </div>
    );
};

// DatabaseAnalysis 组件已移至 ./DatabaseAnalysisTab/index.tsx

const UnitDetailPage: React.FC<UnitDetailPageProps> = ({ unitId }) => {
    const [filter, setFilter] = useState<any>({});
    const [data, setData] = useState<any[]>([]);
    const [allUnits, setAllUnits] = useState<any[]>([]);
    const [unitsLoading, setUnitsLoading] = useState(false);
    const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
    const [loading, setLoading] = useState(false);
    const [unitInfo, setUnitInfo] = useState<any>(null);
    const [statisticsData, setStatisticsData] = useState<any>(null); // 统计数据
    const [queryInfo, setQueryInfo] = useState<string>(''); // 查询条件说明
    const [activeTab, setActiveTab] = useState('basicInfo'); // 当前激活的tab，默认基本信息
    const [loadedTabs, setLoadedTabs] = useState<Set<string>>(new Set(['basicInfo'])); // 记录已加载的tab

    // 导出相关状态
    const [exportLoading, setExportLoading] = useState(false);
    const [exportModalVisible, setExportModalVisible] = useState(false);
    const [exportTaskId, setExportTaskId] = useState<number | null>(null);

    // 扫描相关状态
    const [scanLoading, setScanLoading] = useState(false);

    const navigate = useNavigate();

    // 加载所有单元列表
    const loadAllUnits = useCallback(async () => {
        setUnitsLoading(true);
        try {
            const response = await fetchUnitList({ pageNum: 1, pageSize: 1000 });
            const dataRes = response?.data || response;
            const units = dataRes?.records || [];
            setAllUnits(units);
        } catch (error) {
            console.error('加载单元列表失败:', error);
            setAllUnits([]);
        } finally {
            setUnitsLoading(false);
        }
    }, []);

    const loadUnitInfo = useCallback(async () => {
        if (!unitId) return;
        try {
            console.log('Loading unit info for:', unitId);
            const res = await getUnit(unitId);
            console.log('Unit info response:', res);
            // 兼容不同返回结构 {data: {...} } 或直接 {...}
            const dataRes = (res && res.data) ? res.data : res;
            setUnitInfo(dataRes || null);
        } catch (e: any) {
            console.error('Failed to load unit info:', e);
            // 提供更详细的错误信息
            const errorMessage = e?.response?.data?.msg || e?.message || '加载单元信息失败';
            console.error('Error message:', errorMessage);
            setUnitInfo(null);
            // 可以在这里设置一个错误状态
        }
    }, [unitId]);

    // 加载统计数据（统一在父组件加载，避免重复请求）
    const loadStatisticsData = useCallback(async () => {
        if (!unitId) return;
        try {
            const { getStatisticsOverview } = await import('../../services/statistics');
            const response: any = await getStatisticsOverview(unitId);

            // 处理后端响应格式
            let data = null;
            if (response && typeof response === 'object') {
                if ('code' in response && response.code === 0 && response.data) {
                    data = response.data;
                } else if ('totalFiles' in response || 'totalLines' in response) {
                    data = response;
                }
            }

            setStatisticsData(data);
            console.log('Loaded statistics data (shared):', data);
        } catch (error) {
            console.error('加载统计数据失败:', error);
            setStatisticsData(null);
        }
    }, [unitId]);

    // 处理全量扫描
    const handleFullScan = async () => {
        if (!unitId) {
            message.warning('单元ID不能为空');
            return;
        }

        setScanLoading(true);
        try {
            const response = await manualTriggerScan(unitId);
            if (response.code === 0) {
                message.success('扫描任务已启动，请稍后查看扫描记录');
            } else {
                message.error('启动扫描失败：' + (response.msg || response.message || '未知错误'));
            }
        } catch (error) {
            console.error('启动扫描失败:', error);
            message.error('启动扫描失败，请稍后重试');
        } finally {
            setScanLoading(false);
        }
    };

    // 处理指定类型扫描
    const handleScanByType = async (taskType: string) => {
        if (!unitId) {
            message.warning('单元ID不能为空');
            return;
        }

        setScanLoading(true);
        try {
            const response = await manualTriggerScanByType(unitId, taskType);
            if (response.code === 0) {
                message.success(`${getTaskTypeLabel(taskType)}扫描任务已启动`);
            } else {
                message.error('启动扫描失败：' + (response.msg || response.message || '未知错误'));
            }
        } catch (error) {
            console.error('启动扫描失败:', error);
            message.error('启动扫描失败，请稍后重试');
        } finally {
            setScanLoading(false);
        }
    };

    // 获取任务类型标签
    const getTaskTypeLabel = (taskType: string): string => {
        const taskTypeMap: { [key: string]: string } = {
            'SA': 'SA分析',
            'GIT': 'Git分析',
            'APM': 'APM分析',
            'JAR': 'JAR分析',
            'DB': 'DB分析',
            'STATISTICS': '统计分析',
            'DEPRECATION_ANALYSIS': '废弃分析'
        };
        return taskTypeMap[taskType] || taskType;
    };

    // 创建扫描菜单
    const scanMenuItems = [
        {
            key: 'fullScan',
            icon: <ThunderboltOutlined />,
            label: '全量扫描',
            onClick: () => handleFullScan()
        },
        {
            key: 'divider1',
            type: 'divider' as const
        },
        {
            key: 'JAR',
            label: 'JAR分析',
            onClick: () => handleScanByType('JAR')
        },
        {
            key: 'GIT',
            label: 'Git分析',
            onClick: () => handleScanByType('GIT')
        },
        {
            key: 'APM',
            label: 'APM分析',
            onClick: () => handleScanByType('APM')
        },
        {
            key: 'SA',
            label: 'SA分析',
            onClick: () => handleScanByType('SA')
        },
        {
            key: 'DB',
            label: 'DB分析',
            onClick: () => handleScanByType('DB')
        },
        {
            key: 'DEPRECATION_ANALYSIS',
            label: '废弃分析',
            onClick: () => handleScanByType('DEPRECATION_ANALYSIS')
        },
        {
            key: 'CHANGE_ANALYSIS',
            label: '变更分析',
            onClick: () => handleScanByType('CHANGE_ANALYSIS')
        },
        {
            key: 'STATISTICS',
            label: '统计分析',
            onClick: () => handleScanByType('STATISTICS')
        }
    ];

    const handleSearch = useCallback(async (values: any, pager = { current: 1, pageSize: 10, total: 0 }) => {
        setFilter(values);
        setLoading(true);

        // 构建基础参数
        const params: any = { unitId, pageNum: pager.current, pageSize: pager.pageSize };

        // 处理通用搜索（快速搜索）
        if (values._isQuickSearch) {
            // 快速搜索模式：在包名、类名、方法名中搜索关键词
            const keyword = values.packageName || values.className || values.methodName;
            if (keyword && keyword.trim()) {
                // 使用后端支持的 keyword 字段进行通用搜索
                params.keyword = keyword.trim();
            }
        } else {
            // 精确搜索模式：处理每个字段
            const stringFields = ['className', 'methodName', 'packageName', 'methodSignature', 'serviceName', 'serviceType', 'codeStatus', 'runtimeStatus'];
            stringFields.forEach(field => {
                if (values[field] && values[field].trim() !== '') {
                    params[field] = values[field].trim();
                }
            });
        }

        // 处理布尔字段：只有明确的true/false才传递
        if (values.isEntry !== undefined && values.isEntry !== null && values.isEntry !== '') {
            // 处理字符串形式的布尔值
            if (values.isEntry === 'true' || values.isEntry === true) {
                params.isEntry = true;
            } else if (values.isEntry === 'false' || values.isEntry === false) {
                params.isEntry = false;
            }
        }

        // 处理SA记录筛选
        if (values.hasSaRecord !== undefined && values.hasSaRecord !== null && values.hasSaRecord !== '') {
            if (values.hasSaRecord === 'true' || values.hasSaRecord === true) {
                params.hasSaRecord = true;
            } else if (values.hasSaRecord === 'false' || values.hasSaRecord === false) {
                params.hasSaRecord = false;
            }
        }

        // 处理APM记录筛选
        if (values.hasApmRecord !== undefined && values.hasApmRecord !== null && values.hasApmRecord !== '') {
            if (values.hasApmRecord === 'true' || values.hasApmRecord === true) {
                params.hasApmRecord = true;
            } else if (values.hasApmRecord === 'false' || values.hasApmRecord === false) {
                params.hasApmRecord = false;
            }
        }

        // 处理废弃风险等级筛选
        if (values.deprecationLevel && values.deprecationLevel.trim() !== '') {
            params.deprecationLevel = values.deprecationLevel.trim();
        }

        // 处理时间范围字段：将天数转换为具体的时间查询参数
        // 累计无调用时长（天）- 转换为最后调用时间的时间范围
        if (values.noSaCallDurationDays !== undefined && values.noSaCallDurationDays !== null && values.noSaCallDurationDays !== '') {
            const numValue = Number(values.noSaCallDurationDays);
            if (!isNaN(numValue) && numValue > 0) {
                // 使用工具函数计算对应的时间
                const timeQuery = convertDaysToDateQuery(numValue);

                // 添加调试信息
                console.log(`查询累计无调用时长 >= ${numValue}天，即最后调用时间在 ${timeQuery.formatDisplay} 之前`);

                // 如果后端支持时间范围查询，可以使用这些参数
                // params.lastInvocationTimeBefore = timeQuery.dateString; // YYYY-MM-DD格式
                // params.lastInvocationTimeBeforeTs = timeQuery.timestamp; // 时间戳格式

                // 目前仍然传递天数给后端，让后端处理具体的时间计算
                params.noSaCallDurationDays = numValue;

                // 可以将计算出的时间信息存储，供后续使用
                params._meta = params._meta || {};
                params._meta.noSaCallCutoffDate = timeQuery.formatDisplay;
            }
        }

        // 累计无修改时长（天）- 转换为最后修改时间的时间范围  
        if (values.noCodeChangeDurationDays !== undefined && values.noCodeChangeDurationDays !== null && values.noCodeChangeDurationDays !== '') {
            const numValue = Number(values.noCodeChangeDurationDays);
            if (!isNaN(numValue) && numValue > 0) {
                // 使用工具函数计算对应的时间
                const timeQuery = convertDaysToDateQuery(numValue);

                // 添加调试信息
                console.log(`查询累计无修改时长 >= ${numValue}天，即最后修改时间在 ${timeQuery.formatDisplay} 之前`);

                // 如果后端支持时间范围查询，可以使用这些参数
                // params.gitLastEditTimeBefore = timeQuery.dateString; // YYYY-MM-DD格式
                // params.gitLastEditTimeBeforeTs = timeQuery.timestamp; // 时间戳格式

                // 目前仍然传递天数给后端，让后端处理具体的时间计算
                params.noCodeChangeDurationDays = numValue;

                // 可以将计算出的时间信息存储，供后续使用
                params._meta = params._meta || {};
                params._meta.noCodeChangeCutoffDate = timeQuery.formatDisplay;
            }
        }

        // 处理排序字段
        if (values.orderBy && values.orderBy.trim() !== '') {
            params.orderBy = values.orderBy.trim();
        }
        if (values.orderByType && values.orderByType.trim() !== '') {
            params.orderByType = values.orderByType.trim();
        }

        // 生成查询条件说明
        const queryDescriptions: string[] = [];

        // 存储排序信息到meta中
        if (params.orderBy && params.orderByType) {
            params._meta = params._meta || {};
            params._meta.orderByType = params.orderByType;
        }

        // 检查是否为快速搜索
        if (values._isQuickSearch && params.keyword) {
            queryDescriptions.push(`通用搜索："${params.keyword}" (在包名、类名、方法名中查找)`);
        } else {
            // 处理所有查询条件
            Object.keys(params).forEach(key => {
                if (key === '_meta' || key === 'unitId' || key === 'pageNum' || key === 'pageSize' || key === 'orderByType') {
                    return; // 跳过元数据和分页参数
                }

                const value = params[key];
                if (value !== undefined && value !== null && value !== '') {
                    const description = formatQueryCondition(key, value, params._meta);
                    queryDescriptions.push(description);
                }
            });
        }

        // 设置查询说明
        if (queryDescriptions.length > 0) {
            setQueryInfo(`当前查询条件：${queryDescriptions.join('，')}`);
        } else {
            setQueryInfo('');
        }

        // 输出最终查询参数（用于调试）
        console.log('最终查询参数：', {
            ...params,
            _meta: params._meta || {}
        });

        // 移除元数据，不发送给后端
        if (params._meta) {
            delete params._meta;
        }

        const res = await fetchMethodPageQuery(params);
        const dataRes = res.data || res;
        setData(dataRes.records || []);
        setPagination({ ...pager, total: dataRes.total || 0 });
        setLoading(false);
    }, [unitId]);

    useEffect(() => {
        if (unitId) {
            loadUnitInfo();
            loadStatisticsData(); // 加载统计数据用于头部展示
            loadAllUnits();
            handleSearch({}, { current: 1, pageSize: 10, total: 0 });
        }
    }, [unitId, handleSearch, loadUnitInfo, loadStatisticsData, loadAllUnits]);

    // 表格排序、分页、筛选事件
    const handleTableChange = (pager: any, filters: any, sorter: any) => {
        let orderBy, orderByType;
        if (sorter && sorter.field && sorter.order) {
            orderBy = sorter.field;
            orderByType = sorter.order === 'ascend' ? 'asc' : 'desc';
        }
        handleSearch(
            { ...filter, orderBy, orderByType },
            { current: pager.current, pageSize: pager.pageSize, total: pagination.total }
        );
    };

    // 处理导出
    const handleExport = async (filterValues: any) => {
        try {
            setExportLoading(true);

            const exportParams = {
                unitId,
                ...filterValues
            };

            console.log('导出参数:', exportParams);

            const response = await exportMethods(exportParams);

            if (response && response.data) {
                const taskId = response.data;
                setExportTaskId(taskId);
                setExportModalVisible(true);
                message.success('导出任务已创建，正在后台处理...');
            } else {
                message.error('创建导出任务失败');
            }
        } catch (error: any) {
            console.error('导出失败:', error);
            message.error(error?.response?.data?.msg || '导出失败');
        } finally {
            setExportLoading(false);
        }
    };

    // 检查导出状态
    const handleCheckExportStatus = async (taskId: number) => {
        try {
            const response = await getExportStatus(taskId);
            return {
                status: 'running', // 简化状态处理
                message: response?.data || '正在处理...'
            };
        } catch (error: any) {
            console.error('检查导出状态失败:', error);
            throw error;
        }
    };

    // 下载导出文件
    const handleDownloadExport = (taskId: number) => {
        try {
            downloadExportFile(taskId);
        } catch (error: any) {
            console.error('下载文件失败:', error);
            message.error('下载文件失败');
        }
    };

    // 关闭导出弹窗
    const handleCloseExportModal = () => {
        setExportModalVisible(false);
        setExportTaskId(null);
    };

    // 处理tab切换，标记已加载的tab
    const handleTabChange = (key: string) => {
        setActiveTab(key);
        setLoadedTabs(prev => new Set(Array.from(prev).concat(key)));
    };

    return (
        <div style={{
            background: '#f5f5f5',
            height: '100vh',
            padding: '0',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column'
        }}>
            <div style={{
                background: '#fff',
                borderBottom: '1px solid #f0f0f0',
                padding: '16px 24px',
                position: 'sticky',
                top: 0,
                zIndex: 100,
                boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
            }}>
                {/* 页面标题和操作区域 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center'
                }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flex: 1 }}>
                        <div style={{
                            width: '4px',
                            height: '28px',
                            background: 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)',
                            borderRadius: '2px'
                        }} />
                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                            <div style={{
                                fontSize: '16px',
                                color: '#262626',
                                fontWeight: '500'
                            }}>
                                单元详情
                            </div>
                            <div style={{
                                fontSize: '14px',
                                color: '#8c8c8c',
                                paddingLeft: '12px',
                                borderLeft: '1px solid #f0f0f0'
                            }}>
                                应用瘦身平台
                            </div>
                        </div>

                        {/* 单元信息内容 - 直接嵌入标题栏 */}
                        {unitInfo && (
                            <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '16px',
                                fontSize: '13px',
                                marginLeft: '24px',
                                flex: 1
                            }}>
                                {/* Git仓库 */}
                                <div style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '6px',
                                    minWidth: 0,
                                    flex: '0 1 auto'
                                }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', flexShrink: 0 }}>仓库:</span>
                                    {unitInfo.gitRepoUrl ? (
                                        <a
                                            href={convertSshToHttp(unitInfo.gitRepoUrl).httpUrl}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            style={{
                                                color: '#1890ff',
                                                textDecoration: 'none',
                                                maxWidth: '400px',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap',
                                                fontSize: '12px'
                                            }}
                                            title={unitInfo.gitRepoUrl}
                                        >
                                            {unitInfo.gitRepoUrl}
                                        </a>
                                    ) : (
                                        <span style={{ color: '#bfbfbf' }}>-</span>
                                    )}
                                </div>

                                {/* 分支 */}
                                <div style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '6px',
                                    flexShrink: 0
                                }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px' }}>分支:</span>
                                    <Tag color="blue" style={{ margin: 0, fontSize: '11px', padding: '0 6px', lineHeight: '20px' }}>
                                        {unitInfo.currentBranch || unitInfo.defaultBranch || 'master'}
                                    </Tag>
                                </div>

                                {/* 数据状态 */}
                                <div style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '6px',
                                    flexShrink: 0
                                }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px' }}>数据:</span>
                                    <UnitInfoStatusBadges unitId={unitId} unitInfo={unitInfo} statisticsData={statisticsData} />
                                </div>
                            </div>
                        )}
                    </div>

                    {/* 快捷操作按钮组 */}
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                            <Button
                                type="text"
                                size="middle"
                                icon={<ArrowLeftOutlined />}
                                onClick={() => {
                                    if (window.history.length > 1) {
                                        window.history.back();
                                    } else {
                                        navigate('/units');
                                    }
                                }}
                                style={{
                                    color: '#8c8c8c',
                                    fontSize: '14px'
                                }}
                            >
                                返回
                            </Button>

                            <div style={{ width: '1px', height: '20px', background: '#f0f0f0' }} />

                            <Button
                                type="text"
                                size="middle"
                                icon={<SyncOutlined />}
                                onClick={() => window.location.reload()}
                                style={{
                                    color: '#8c8c8c',
                                    fontSize: '14px'
                                }}
                            >
                                刷新
                            </Button>

                            <div style={{ width: '1px', height: '20px', background: '#f0f0f0' }} />

                            <Dropdown
                                menu={{ items: scanMenuItems }}
                                trigger={['click']}
                                placement="bottomRight"
                            >
                                <Button
                                    type="default"
                                    size="middle"
                                    loading={scanLoading}
                                    icon={<PlayCircleOutlined />}
                                    style={{
                                        color: '#52c41a',
                                        borderColor: '#52c41a',
                                        fontSize: '14px'
                                    }}
                                >
                                    启动扫描 <CaretDownOutlined />
                                </Button>
                            </Dropdown>

                            <Button
                                type="primary"
                                size="middle"
                                icon={<EditOutlined />}
                                onClick={() => navigate(`/unit/${unitId}/edit`)}
                                style={{
                                    borderRadius: '6px',
                                    backgroundColor: '#1890ff',
                                    borderColor: '#1890ff',
                                    boxShadow: '0 2px 8px rgba(24, 144, 255, 0.2)'
                                }}
                            >
                                编辑
                            </Button>
                        </div>
                    </div>
                </div>
            </div>

            {/* Tab导航和内容区域 */}
            <div style={{
                padding: '0 24px 24px',
                flex: 1,
                minHeight: 0,
                display: 'flex',
                flexDirection: 'column'
            }}>
                <div style={{
                    marginTop: '8px',
                    background: '#fff',
                    borderRadius: '12px',
                    boxShadow: '0 2px 12px rgba(0,0,0,0.08)',
                    border: '1px solid #f0f0f0',
                    overflow: 'hidden',
                    flex: 1,
                    minHeight: 0,
                    display: 'flex',
                    flexDirection: 'column'
                }}>
                    {/* 自定义标签导航栏 */}
                    <div style={{
                        background: 'linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%)',
                        borderBottom: '1px solid #f0f0f0',
                        padding: '0 24px',
                        minHeight: '48px',
                        maxHeight: '48px',
                        display: 'flex',
                        alignItems: 'center'
                    }}>
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '4px',
                            overflowX: 'auto',
                            scrollbarWidth: 'none', // Firefox
                            msOverflowStyle: 'none', // IE and Edge
                            WebkitOverflowScrolling: 'touch' // iOS smooth scrolling
                        }}
                            className="hide-scrollbar"
                        >
                            {[
                                { key: 'basicInfo', label: '基本信息', icon: InfoCircleOutlined },
                                { key: 'codeScaleAnalysis', label: '体量分析', icon: BarChartOutlined },
                                { key: 'methodAnalysis', label: '方法分析', icon: FunctionOutlined },
                                // { key: 'summaryAnalysis', label: '汇总分析', icon: BarChartOutlined }, // 暂时隐藏API汇总统计分析
                                { key: 'apiAnalysis', label: 'API分析', icon: ApiOutlined },
                                { key: 'changeAnalysis', label: '变更分析', icon: LineChartOutlined },
                                { key: 'dubboAnalysis', label: 'Dubbo依赖', icon: ThunderboltOutlined },
                                { key: 'callGraph', label: '调用关系', icon: ShareAltOutlined },
                                { key: 'databaseAnalysis', label: '数据库', icon: DatabaseOutlined },
                                { key: 'assistant', label: '智能助手', icon: CustomerServiceOutlined },
                                { key: 'scanRecords', label: '扫描记录', icon: FileTextOutlined },
                                { key: 'dependencyAnalysis', label: '依赖分析', icon: BarChartOutlined }
                                // { key: 'configManagement', label: '配置', icon: SettingOutlined } // 暂时隐藏配置页面
                            ].map((tab) => {
                                const Icon = tab.icon;
                                const isActive = activeTab === tab.key;
                                return (
                                    <div
                                        key={tab.key}
                                        onClick={() => handleTabChange(tab.key)}
                                        style={{
                                            padding: '12px 16px',
                                            cursor: 'pointer',
                                            display: 'flex',
                                            alignItems: 'center',
                                            gap: '6px',
                                            fontSize: '13px',
                                            fontWeight: isActive ? '600' : '500',
                                            color: isActive ? '#1890ff' : '#8c8c8c',
                                            background: isActive ? '#fff' : 'transparent',
                                            borderRadius: isActive ? '8px 8px 0 0' : '0',
                                            border: isActive ? '1px solid #f0f0f0' : '1px solid transparent',
                                            borderBottom: isActive ? '1px solid #fff' : '1px solid transparent',
                                            marginBottom: isActive ? '-1px' : '0',
                                            position: 'relative',
                                            transition: 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)',
                                            transform: isActive ? 'translateY(1px)' : 'translateY(0)',
                                            zIndex: isActive ? 10 : 1,
                                            whiteSpace: 'nowrap',
                                            flexShrink: 0
                                        }}
                                        onMouseEnter={(e) => {
                                            if (!isActive) {
                                                (e.target as HTMLElement).style.color = '#595959';
                                                (e.target as HTMLElement).style.background = 'rgba(255,255,255,0.6)';
                                            }
                                        }}
                                        onMouseLeave={(e) => {
                                            if (!isActive) {
                                                (e.target as HTMLElement).style.color = '#8c8c8c';
                                                (e.target as HTMLElement).style.background = 'transparent';
                                            }
                                        }}
                                    >
                                        <Icon style={{ fontSize: '16px' }} />
                                        {tab.label}
                                        {isActive && (
                                            <div style={{
                                                position: 'absolute',
                                                bottom: '-1px',
                                                left: '50%',
                                                transform: 'translateX(-50%)',
                                                width: '24px',
                                                height: '3px',
                                                background: 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)',
                                                borderRadius: '2px 2px 0 0'
                                            }} />
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* 内容区域 */}
                    <div style={{
                        flex: 1,
                        overflow: 'auto',
                        position: 'relative',
                        minHeight: 0  // 重要：确保 flex 子元素可以正确收缩
                    }}>
                        {activeTab === 'basicInfo' && (
                            <div style={{ padding: '24px' }}>
                                <BasicInfo
                                    unitId={unitId}
                                    unitInfo={unitInfo}
                                    statisticsData={statisticsData}
                                    onRefreshStatistics={loadStatisticsData}
                                />
                            </div>
                        )}
                        {activeTab === 'codeScaleAnalysis' && loadedTabs.has('codeScaleAnalysis') && (
                            <div style={{ padding: '24px' }}>
                                <CodeScaleAnalysis unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'methodAnalysis' && loadedTabs.has('methodAnalysis') && (
                            <div style={{ padding: '24px' }}>
                                <MethodAnalysis
                                    data={data}
                                    pagination={pagination}
                                    loading={loading}
                                    queryInfo={queryInfo}
                                    unitInfo={unitInfo}
                                    onSearch={(values, pager) => handleSearch(values, pager || { current: 1, pageSize: pagination.pageSize, total: pagination.total })}
                                    onTableChange={handleTableChange}
                                    onClearQuery={() => {
                                        setQueryInfo('');
                                        handleSearch({}, { current: 1, pageSize: pagination.pageSize, total: 0 });
                                    }}
                                    onExport={handleExport}
                                    exportLoading={exportLoading}
                                />
                            </div>
                        )}
                        {/* 暂时隐藏汇总分析页面 */}
                        {/* {activeTab === 'summaryAnalysis' && loadedTabs.has('summaryAnalysis') && (
                            <div>
                                <ApiSummaryAnalysis unitId={unitId} />
                            </div>
                        )} */}
                        {activeTab === 'apiAnalysis' && loadedTabs.has('apiAnalysis') && (
                            <div>
                                <ApiAnalysisTab unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'changeAnalysis' && loadedTabs.has('changeAnalysis') && (
                            <div>
                                <ChangeAnalysisTab unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'dubboAnalysis' && loadedTabs.has('dubboAnalysis') && (
                            <div>
                                <DubboAnalysisTab unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'callGraph' && loadedTabs.has('callGraph') && (
                            <div style={{ padding: '16px' }}>
                                <CallGraphTab unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'databaseAnalysis' && loadedTabs.has('databaseAnalysis') && (
                            <div style={{ padding: '24px' }}>
                                <DatabaseAnalysisTab unitId={unitId} unitInfo={unitInfo} />
                            </div>
                        )}
                        {activeTab === 'assistant' && loadedTabs.has('assistant') && (
                            <div style={{ height: 'calc(100vh - 180px)' }}>
                                <AssistantTab unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'scanRecords' && loadedTabs.has('scanRecords') && (
                            <div>
                                <ScanRecords unitId={unitId} />
                            </div>
                        )}
                        {activeTab === 'dependencyAnalysis' && loadedTabs.has('dependencyAnalysis') && (
                            <div style={{ padding: '24px' }}>
                                <DependencyAnalysis />
                            </div>
                        )}
                        {activeTab === 'configManagement' && loadedTabs.has('configManagement') && (
                            <div style={{ padding: '24px' }}>
                                <ConfigManagement unitInfo={unitInfo} />
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* 导出进度弹窗 */}
            <ExportProgressModal
                visible={exportModalVisible}
                taskId={exportTaskId}
                onClose={handleCloseExportModal}
                onCheckStatus={handleCheckExportStatus}
                onDownload={handleDownloadExport}
            />
        </div>
    );
};

export default UnitDetailPage; 
